﻿function userController($scope, $http) {
    $scope.loading = true;
    $scope.addMode = false;

    //Used to display the data  
    $http.get('/api/User/Getusers').success(function (data) {
        $scope.users = data;
        $scope.loading = false;
    })
    .error(function () {
        $scope.error = "An Error has occured while loading posts!";
        $scope.loading = false;
    });

    $scope.toggleEdit = function () {
        this.user.editMode = !this.user.editMode;
    };
    $scope.toggleAdd = function () {
        $scope.addMode = !$scope.addMode;
    };

    //Used to save a record after edit  
    $scope.save = function () {
        alert("Edit");
        $scope.loading = true;
        var u = this.user;
        //alert(emp);
        $http.put('/api/User/Putuser/', u).success(function (data) {
            alert("Saved Successfully!!");
            u.editMode = false;
            $scope.loading = false;
        }).error(function (data) {
            $scope.error = "An Error has occured while Saving Friend! " + data;
            $scope.loading = false;

        });
    };

    //Used to add a new record  
    $scope.add = function () {
        $scope.loading = true;
        $http.post('/api/Postuser/', this.newUser).success(function (data) {
            alert("Added Successfully!!");
            $scope.addMode = false;
            $scope.users.push(data);
            $scope.loading = false;
        }).error(function (data) {
            $scope.error = "An Error has occured while Adding Friend! " + data;
            $scope.loading = false;

        });
    };

    //Used to edit a record  
    $scope.deleteUser = function () {
        $scope.loading = true;
        var uId = this.user.Id;
        $http.delete('/api/User/' + uId).success(function (data) {
            alert("Deleted Successfully!!");
            $.each($scope.users, function (i) {
                if ($scope.users[i].Id === uId) {
                    $scope.users.splice(i, 1);
                    return false;
                }
            });
            $scope.loading = false;
        }).error(function (data) {
            $scope.error = "An Error has occured while Saving Friend! " + data;
            $scope.loading = false;

        });
    };
}